<template>
  <div class="announcement-container">
    <h2 class="title">{{ isEditMode ? '编辑公告' : '新增公告' }}</h2>

    <el-form :model="form" label-width="100px" class="announcement-form">
      <el-form-item label="消息标题" required>
        <el-input v-model="form.messageTitle" placeholder="请输入消息标题" />
      </el-form-item>

      <el-form-item label="消息内容" required>
        <el-input
            v-model="form.messageContent"
            type="textarea"
            :rows="5"
            placeholder="请输入消息内容"
        />
      </el-form-item>

      <el-form-item label="消息状态" required>
        <el-select v-model="form.status">
          <el-option
              v-for="item in statusOptions"
              :key="item.key"
              :label="item.value"
              :value="item.key"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="发布时间" required>
        <el-date-picker
            v-model="form.publishTime"
            type="datetime"
            placeholder="选择发布时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>

      <el-form-item label="发布人">
        <el-input v-model="form.doctor.name" placeholder="发布人" readonly />
      </el-form-item>

      <el-form-item label="生成时间">
        <el-input v-model="form.createTime" :value="formatDateTimeForDisplay(form.createTime)" placeholder="生成时间" readonly >
        </el-input>
      </el-form-item>

      <el-form-item label="接收人">
        <el-button type="primary" @click="showReceiverDialog">选择接收人</el-button>

        <div class="selected-receivers" v-if="selectedReceivers.length > 0">
          <el-table :data="selectedReceivers" border style="width: 100%; margin-top: 10px;" :key="receiversTableKey">
            <el-table-column prop="id" label="编号" width="80" />
            <el-table-column label="头像" width="80">
              <template #default="{ row }">
                <el-avatar :size="40" :src="row.avatar || ''" />
              </template>
            </el-table-column>
            <el-table-column prop="name" label="姓名" width="120" />
            <el-table-column prop="contactPhone" label="联系电话" width="150" />
            <el-table-column prop="role.roleName" label="角色" width="120" />
            <el-table-column prop="team.teamName" label="所属团队" />
            <el-table-column label="操作" width="100">
              <template #default="{ $index }">
                <el-button type="danger" size="small" @click="removeReceiver($index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-else class="no-receivers">暂无已选接收人</div>
      </el-form-item>

      <el-form-item class="form-actions">
        <el-button type="primary" @click="handlePublish">发布</el-button>
        <el-button @click="handleCancel">返回</el-button>
      </el-form-item>
    </el-form>

    <!-- 选择接收人弹窗 -->
    <el-dialog
        v-model="receiverDialogVisible"
        title="选择接收人"
        width="80%"
        top="5vh"
        @close="handleDialogClose"
    >
      <div class="receiver-dialog-content">
        <div class="search-header">
          <el-select
              v-model="searchForm.teamId"
              placeholder="请选择医生团队"
              clearable
              style="width: 200px; margin-right: 10px;"
              @change="handleTeamChange"
          >
            <el-option
                v-for="team in teamOptions"
                :key="team.id"
                :label="team.teamName"
                :value="team.id"
            />
          </el-select>

          <el-input
              v-model="searchForm.keyword"
              placeholder="请输入关键字"
              style="width: 200px; margin-right: 10px;"
              @input="handleKeywordInput"
          />

          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>

          <el-button type="success" @click="selectAllReceivers">选择所有人</el-button>
          <el-button type="info" @click="deselectAllReceivers">取消全选</el-button>
        </div>

        <el-table :data="receiverList" border style="width: 100%; margin-top: 20px;" :key="searchTableKey">
          <el-table-column width="60">
            <template #header>
              <el-checkbox v-model="isAllSelected" @change="handleSelectAll" />
            </template>
            <template #default="{ row }">
              <el-checkbox
                  v-model="row.checked"
                  @change="handleSelectChange(row)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="id" label="编号" width="80" />
          <el-table-column label="头像" width="80">
            <template #default="{ row }">
              <el-avatar :size="40" :src="row.avatar" />
            </template>
          </el-table-column>
          <el-table-column prop="name" label="姓名" width="120" />
          <el-table-column prop="contactPhone" label="联系电话" width="150" />
          <el-table-column prop="role.roleName" label="角色" width="120" />
          <el-table-column prop="team.teamName" label="所属团队" />
        </el-table>

        <div class="pagination">
          <el-pagination
              v-model:current-page="searchForm.page"
              v-model:page-size="searchForm.pageSize"
              :total="totalReceivers"
              layout="total, sizes, prev, pager, next, jumper"
              :page-sizes="[10, 20, 50, 100]"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
          />
        </div>
      </div>

      <template #footer>
        <el-button @click="receiverDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmReceivers">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import {formatDateTime, formatDateTimeForDisplay} from '@/utils/dateUtil.js'
import { useRoute, useRouter } from 'vue-router'
import axios from "axios";
//pinia使用
import { userStore } from '/src/components/store/index.js'
import request from "@/utils/request.js";
const userItemStore = userStore();


// 路由相关
const route = useRoute();
const router = useRouter();

// 状态选项
const statusOptions = [
  { key: 0, value: '待发布' },
  { key: 1, value: '已发布' }
];

// 表格刷新标识
const receiversTableKey = ref(0);
const searchTableKey = ref(0);

// 全选状态
const isAllSelected = ref(false);

// 表单数据
const form = reactive({
  id: null,
  messageTitle: '',
  messageContent: '',
  status: null,
  publishTime: '',
  createTime: '',
  lastupdateTime: '',
  roleId: null,
  doctorIdSend: null,
  doctor: { id: null, name: '' },
  receiverIds: [] // 存储接收人ID数组
});

// 已选择的接收人列表
const selectedReceivers = ref([]);
// 获取已选择的接收人列表（根据receiverIds）
const fetchSelectedReceivers = () => {
  if (form.receiverIds.length === 0) {
    selectedReceivers.value = [];
    return;
  }

  request.post('/doctor/getDoctorByBatchId', { receiverIds: form.receiverIds }).then(resp => {
    selectedReceivers.value = resp.data;
    receiversTableKey.value++;
  });
};



// 接收人弹窗相关
const receiverDialogVisible = ref(false);
const receiverList = ref([]);
const totalReceivers = ref(0);
const selectedReceiverIds = ref(new Set()); // 选中的ID集合
const teamOptions = ref([]);
const allReceiversData = ref([]); // 全部接收人数据

// 搜索表单
const searchForm = reactive({
  teamId: null,
  keyword: '',
  page: 1,
  pageSize: 10
});

// 获取团队列表
const getTeamOptions = () => {
  request.get('/team/getAllTeam').then(resp => {
    teamOptions.value = resp.data;
  });
};


// 获取全部接收人列表（用于弹窗）
const fetchAllReceivers = () => {
  request.post(`/doctor/getAllDoctors`,searchForm).then(resp => {
    allReceiversData.value = resp.data;
    updateReceiverList();
  });
};

// 更新弹窗中的接收人列表
const updateReceiverList = () => {
  let data = allReceiversData.value || [];

  // 分页处理
  const start = (searchForm.page - 1) * searchForm.pageSize;
  const end = start + searchForm.pageSize;
  const paginatedData = data.slice(start, end);

  // 标记已选中的接收人
  receiverList.value = paginatedData.map(item => ({
    ...item,
    checked: selectedReceiverIds.value.has(item.id)
  }));

  isAllSelected.value = receiverList.value.every(item => item.checked);
  totalReceivers.value = data.length;
  searchTableKey.value++;
};

// 处理选择变化
const handleSelectChange = (row) => {
  if (row.checked) selectedReceiverIds.value.add(row.id);
  else selectedReceiverIds.value.delete(row.id);

  updateAllSelectedStatus();
  updateReceiverIdsList();
};

// 全选当前页
const handleSelectAll = () => {
  if (isAllSelected.value) {
    receiverList.value.forEach(item => {
      if (!selectedReceiverIds.value.has(item.id)) {
        selectedReceiverIds.value.add(item.id);
        item.checked = true;
      }
    });
  } else {
    receiverList.value.forEach(item => {
      if (selectedReceiverIds.value.has(item.id)) {
        selectedReceiverIds.value.delete(item.id);
        item.checked = false;
      }
    });
  }

  updateReceiverIdsList();
};

// 选择所有人（跨页全选）
const selectAllReceivers = () => {
  selectedReceiverIds.value.clear();
  const allFilteredReceivers = getFilteredReceivers();

  allFilteredReceivers.forEach(item => {
    selectedReceiverIds.value.add(item.id);
  });

  fetchAllReceivers();
  updateReceiverIdsList();
  ElMessage.success(`已选中 ${allFilteredReceivers.length} 个接收人`);
};

// 取消全选
const deselectAllReceivers = () => {
  selectedReceiverIds.value.clear();
  fetchAllReceivers();
  updateReceiverIdsList();
  ElMessage.success('已取消选择所有接收人');
};

// 获取过滤后的接收人列表
const getFilteredReceivers = () => {
  let data = allReceiversData.value || [];

  return data;
};

// 更新全选状态
const updateAllSelectedStatus = () => {
  if (receiverList.value.length === 0) {
    isAllSelected.value = false;
    return;
  }
  isAllSelected.value = receiverList.value.every(item => item.checked);
};

// 更新接收人ID列表
const updateReceiverIdsList = () => {
  form.receiverIds = Array.from(selectedReceiverIds.value);
  fetchSelectedReceivers(); // 重新获取已选择的接收人
};

// 对话框关闭时更新接收人列表
const handleDialogClose = () => {
  updateReceiverIdsList();
};

// 团队选择变化
const handleTeamChange = () => {
  searchForm.page = 1;
  fetchAllReceivers();
};

// 关键字输入
const handleKeywordInput = () => {
  searchForm.page = 1;
  fetchAllReceivers();
};

// 显示接收人对话框
const showReceiverDialog = () => {
  receiverDialogVisible.value = true;
  fetchAllReceivers();
};

// 搜索接收人
const handleSearch = () => {
  searchForm.page = 1;
  fetchAllReceivers();
};

// 重置搜索条件
const resetSearch = () => {
  searchForm.teamId = '';
  searchForm.keyword = '';
  handleSearch();
};

// 分页相关
const handleSizeChange = (val) => {
  searchForm.pageSize = val;
  fetchAllReceivers();
};

const handlePageChange = (val) => {
  searchForm.page = val;
  fetchAllReceivers();
};

// 确认选择的接收人
const confirmReceivers = () => {
  updateReceiverIdsList();
  receiverDialogVisible.value = false;
  ElMessage.success(`已选择 ${form.receiverIds.length} 个接收人`);
};



// 删除接收人
const removeReceiver = (index) => {
  const removedId = form.receiverIds[index];
  form.receiverIds.splice(index, 1);
  selectedReceiverIds.value.delete(removedId);

  // 更新弹窗中的选中状态
  if (receiverDialogVisible.value) {
    const receiver = receiverList.value.find(item => item.id === removedId);
    if (receiver) receiver.checked = false;
    updateAllSelectedStatus();
  }

  fetchSelectedReceivers();
  receiversTableKey.value++;
};


// 修改发布方法
const handlePublish = async () => {
  if (!form.messageTitle) { ElMessage.warning('请输入消息标题'); return; }
  if (!form.messageContent) { ElMessage.warning('请输入消息内容'); return; }
  if (!form.publishTime) { ElMessage.warning('请选择发布时间'); return; }
  if (form.receiverIds.length === 0) { ElMessage.warning('请选择接收人'); return; }

  try {
    // 确保使用最新的 store 数据
    const currentUser = userItemStore.user;
    console.log('Current user:', currentUser); // 调试

    // 使用 Object.assign 确保响应式更新
    Object.assign(form, {
      lastupdateTime: formatDateTime(new Date()).iso,
      publishTime: formatDateTime(new Date()).iso,
      roleId: currentUser.doctorRoleId,
      doctorIdSend: currentUser.id,
      // 如果是新增，添加创建时间
      ...(!isEditMode.value && { createTime: formatDateTime(new Date()).iso })
    });

    const submitData = {
      ...form,
      receiverIds: form.receiverIds
    };

    console.log('Submitting data:', submitData); // 调试

    const url = isEditMode.value
        ? '/announcement/updateAnnouncement'
        : '/announcement/newAnnouncement';
    const method = isEditMode.value ? 'put' : 'post';

    const response = await request[method](url, submitData);
    ElMessage.success(response.data);
    router.go(-1);
  } catch (error) {
    console.error('提交失败:', error);
    ElMessage.error('提交失败: ' + (error.response?.data?.message || error.message));
  }
};

// 取消操作
const handleCancel = () => {
  router.go(-1);
  // router.push('/system/systemAnnouncement');//该代码无法运行；？？？？
};

// 重置表单
const resetForm = () => {
  form.messageTitle = '';
  form.messageContent = '';
  form.status = null;
  form.publishTime = '';
  form.lastupdateTime = formatDateTime(new Date()).displayFormat;
  form.receiverIds = [];
  selectedReceiverIds.value.clear();
  selectedReceivers.value = [];
  receiversTableKey.value++;
};

// 是否为编辑模式
const isEditMode = ref(false);

// 获取公告详情（编辑模式）
const getAnnouncementById = async (id) => {
  try {
    const resp = await request.get(`/announcement/getAnnById/${id}`);
    Object.assign(form, resp.data);

    // 处理接收人ID
    if (resp.data.receiverIds?.length > 0) {
      selectedReceiverIds.value = new Set(
          Array.isArray(resp.data.receiverIds)
              ? resp.data.receiverIds.map(Number)
              : String(resp.data.receiverIds).split(',').map(Number)
      );
      await fetchSelectedReceivers(); // 等待接收人加载
    } else {
      selectedReceivers.value = []; // 清空已选列表
    }
  } catch (error) {
    console.error('加载公告失败:', error);
    ElMessage.error('加载公告详情失败');
  }
};

// 初始化
onMounted(() => {
  isEditMode.value = route.query.action === 'edit';

  getTeamOptions();

  if (isEditMode.value && route.query.id) {
    getAnnouncementById(route.query.id);
  } else {
    resetForm();
  }

});
</script>

<style scoped>
.announcement-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.title {
  margin-bottom: 20px;
  color: #333;
  text-align: center;
}

.announcement-form {
  max-width: 1000px;
  margin: 0 auto;
}

.form-actions {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.search-header {
  display: flex;
  margin-bottom: 20px;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.receiver-dialog-content {
  padding: 10px;
}

.selected-receivers {
  margin-top: 10px;
}

.no-receivers {
  margin-top: 10px;
  padding: 10px;
  text-align: center;
  color: #999;
  border: 1px dashed #eee;
  border-radius: 4px;
}
</style>